package com.dog.modules.iot.mqtt.produce.bound;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.annotation.JSONField;
import com.dog.modules.iot.mqtt.codec.AES;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Base64;

/**
 * 发送给设备的消息体父类
 * 需要转化为string
 *
 */
@Data
@Slf4j
public class OutboundCommand<T> {
    /**
     * "header":{
     * "cmd":xxxx
     * }
     */
    protected OutboundHeader header;

    /**
     * 消息体
     */
    @JSONField(serialize = false)
    private T payload;


    /**
     * 加密消息体
     */
    protected String data;

    public OutboundCommand(Integer command, T payload) {
        this.header = new OutboundHeader(command);
        this.header.setCmd(command);
        this.payload = payload;
    }

    public OutboundCommand(OutboundHeader header, String data) {
        this.header = header;
        this.data = data;
    }

    /**
     * 对下发指令的消息体进行加密
     *
     * @param secret
     * @param iv
     */
    public void encodeData(byte[] secret, byte[] iv) {
        if (payload == null) {
            log.warn("this is a no payload message!");
            return;
        }
        String payloadStr = JSON.toJSONString(payload);
        log.info("BaseOutCommand encodeData: " + payloadStr);
        //使用固定密钥和AES对称加密方式对payload消息体进行加密
        byte[] ret = AES.encode(payloadStr.getBytes(), secret, iv);
        log.info("BaseOutCommand encodeData aes length: " + ret.length);
        //对加密之后的消息体进行base64编码
        data = Base64.getEncoder().encodeToString(ret);
        log.info("BaseOutCommand encodeData base64 encodeData: " + data);
    }

    /**
     * json序列化string
     *
     * @return
     */
    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
